<template>
  <div class="page gray-page inspect-page">
    <nav-bar :title="title" border></nav-bar>
    <div class="page-main" style="margin-top: 44px">
      <inspect-head v-model="gridCode" type="grid" @change="handleChange"></inspect-head>
      <div class="inspect-map" id="container"></div>
      <inspect-button
        ref="inspectButton"
        background="#ffffff"
        v-show="inspectPoint.length && !$route.query.date"
        @changeStatus="getInspect"
      ></inspect-button>
    </div>
    <van-popup
      v-model="statisticsPopupOpenShow"
      round
      position="bottom"
      :overlay="false"
      class="inspect-statistics-popup"
      :class="{
        'inspect-statistics-popup__bottom':
          inspectRecord.length < 2 || (inspectRecord[1] && inspectRecord[1].inspectionState !== '3')
      }"
      closeable
      close-icon-position="top-center"
      :close-icon="require('@/assets/images/inspectVisit/inspect/icon_popup_shrink@2x.png')"
    >
      <inspect-statistics ref="inspectStatistics" v-show="inspectRecord.length"></inspect-statistics>
    </van-popup>
  </div>
</template>
<script>
import CampusSecurity from '@/api/campussecurity'
import InspectHead from './component/head.vue'
import InspectStatistics from './component/statistics.vue'
import InspectButton from './component/button.vue'
import { formatTimes } from '@/libs/tool'
import mapPlugin from '@/libs/mapPlugin'
export default {
  components: { InspectHead, InspectStatistics, InspectButton },
  data() {
    return {
      title: '校园巡检',
      gridCode: '',
      inspectPoint: [],
      inspectRecord: [],
      statisticsPopupShow: false,
      statisticsPopupOpenShow: false,
      // 地图
      map: null,
      center: [],
      markers: [],
      startEndMarkers: [],
      overlayGroup: null,
      startEndOverlayGroup: null,
      Polylines: []
    }
  },
  created() {
    this.gridCode = this.$route.query.gridCode
  },
  mounted() {
    this.map = new AMap.Map('container', {
      resizeEnable: true,
      zoom: 16
    })
  },
  methods: {
    getInspect() {
      CampusSecurity.Api.list({
        gridCode: this.gridCode,
        date: this.$route.query.date || formatTimes.formatDate(new Date())
      }).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          this.inspectPoint = data.gridInspectionPoint
          this.inspectRecord = data.gridInspectionRecord
          this.statisticsPopupShow = Boolean(this.inspectRecord.length)
          this.statisticsPopupOpenShow = Boolean(this.inspectRecord.length)
          this.inspectPoint.length && this.setMarker()
          this.inspectRecord.length && this.setMarker1()
          this.$nextTick(() => {
            // 按钮组件
            if (this.$refs.inspectButton) {
              this.$refs.inspectButton.inspectPoint = this.inspectPoint
              this.$refs.inspectButton.inspectRecord = this.inspectRecord
              this.$refs.inspectButton.gridCode = this.gridCode
            }
            // 统计组件
            if (this.$refs.inspectStatistics) {
              this.$refs.inspectStatistics.inspectRecord = this.inspectRecord
            }
          })
        }
      })
    },
    // 切换网格
    handleChange(v, item) {
      // 设置中心点
      this.center = [item.longitude, item.latitude]
      this.map.setCenter(this.center)
      this.getPeoplePoint()
      this.map.setZoom(16)
      if (this.overlayGroup) {
        this.map.remove(this.overlayGroup)
        this.overlayGroup = null
        this.markers = []
      }
      if (this.startEndOverlayGroup) {
        this.map.remove(this.startEndOverlayGroup)
        this.startEndOverlayGroup = null
        this.startEndMarkers = []
      }
      if (this.Polylines) {
        this.map.remove(this.Polylines)
      }
      this.getInspect()
    },
    // 已巡查画线
    setMarker1() {
      // 折线的节点坐标数组，每个元素为 AMap.LngLat 对象
      var path = []
      this.Polylines = []
      for (const [index, item] of new Map(this.inspectRecord.map((item, index) => [index, item]))) {
        path[index] = {}
        path[index].path = []
        path[index].color = index === 0 ? 'red' : 'yellow'
        const startImg = require('@/assets/images/gridMap/gridMap-start@2x.png')
        const endImg = require('@/assets/images/gridMap/gridMap-end@2x.png')
        var startmarkers, endmarkers
        if (item.startLongitude && item.startLatitude) {
          startmarkers = new AMap.Marker({
            position: new AMap.LngLat(item.startLongitude, item.startLatitude),
            content: `
              <div class="amap-marker-inspect-gridMap-location">
                <img src="${startImg}" width="32px" alt="">
              </div>`
          })
        }
        if (item.endLongitude && item.endLatitude) {
          endmarkers = new AMap.Marker({
            position: new AMap.LngLat(item.endLongitude, item.endLatitude),
            content: `
              <div class="amap-marker-inspect-gridMap-location">
                <img src="${endImg}" width="32px" alt="">
              </div>`
          })
        }

        if (startmarkers) {
          this.startEndMarkers.push(startmarkers)
        }
        if (endmarkers) {
          this.startEndMarkers.push(endmarkers)
        }
        for (const o of item.inspectionPointRecordList) {
          path[index].path.push(new AMap.LngLat(o.longitude, o.latitude))
        }
        this.Polylines.push(
          new AMap.Polyline({
            path: path[index].path,
            strokeWeight: index === 0 ? 8 : 4, // 线条宽度，默认为 1
            strokeColor: index === 0 ? 'red' : 'yellow', // 线条颜色
            lineJoin: 'round' // 线条颜色
          })
        )
      }
      if (this.startEndMarkers.length) {
        this.startEndOverlayGroup = new AMap.OverlayGroup(this.startEndMarkers)
        this.map.add(this.startEndOverlayGroup)
      }
      this.Polylines.forEach(line => {
        this.map.add(line)
      })
    },
    // 添加marker
    setMarker() {
      for (const item of this.inspectPoint) {
        let lastStatus = 'inspect'
        let statusStr = '<p>今日未巡查</p>'
        if (item.inspectionPointRecord.length) {
          // 最后一条巡查点状态
          const last = item.inspectionPointRecord[item.inspectionPointRecord.length - 1]
          lastStatus = last.inspectionResult === '1' ? 'abnormal' : 'normal'
          // 每条巡查点状态
          statusStr = ''
          for (const o of item.inspectionPointRecord) {
            const classStr = o.inspectionResult === '1' ? 'abnormal' : 'normal'
            statusStr += `<p class="${classStr}">
              ${o.inspectionTime}
              <i class="van-icon van-icon-${o.inspectionResult === '1' ? 'warning' : 'checked'}"></i>
            </p>`
          }
        }
        // marker
        const img = require(`@/assets/images/inspectVisit/inspect/icon_map_${lastStatus}@2x.png`)
        // <p>${item.inspectionPointName}</p>
        const content = `
        <div class="amap-marker-inspect-content">
            <img src="${img}" width="32px" alt="">
            <div class="${lastStatus}">${statusStr}</div>
        </div>`
        const marker = new AMap.Marker({
          position: new AMap.LngLat(item.longitude, item.latitude),
          content: content
        })
        this.markers.push(marker)

        // 点击
        marker.on('click', () => {
          if (item.inspectionPointRecord.length) {
            // 已巡查
            this.$router.push({
              path: '/campusSecurity/SafetyInspection/StartedToPatrol/report',
              query: {
                gridCode: this.gridCode,
                inspectionPointCode: item.inspectionPointCode,
                inspectionPointName: item.inspectionPointName,
                inspectionTime: formatTimes.formatDate(new Date(item.inspectionPointRecord[0].inspectionTime)),
                companyCode: this.inspectRecord[this.inspectRecord.length - 1].inspectionRecordCode,
                type: 'detail'
              }
            })
          } else if (
            this.inspectRecord.length &&
            this.inspectRecord[this.inspectRecord.length - 1].inspectionState === '1'
          ) {
            // 未巡查
            mapPlugin.geolocation(result => {
              const lnglat1 = result.position
              const lnglat2 = [item.longitude, item.latitude]
              const distance = lnglat1.distance(lnglat2)
              console.log(distance)
              if (distance <= 1000000) {
                this.$router.push({
                  path: '/campusSecurity/SafetyInspection/StartedToPatrol/report',
                  query: {
                    gridCode: this.gridCode,
                    inspectionPointCode: item.inspectionPointCode,
                    inspectionPointName: item.inspectionPointName,
                    companyCode: this.inspectRecord[this.inspectRecord.length - 1].inspectionRecordCode
                  }
                })
              } else {
                this.$toast({
                  message: '距离当前巡查点过远，请重试',
                  position: 'bottom'
                })
              }
            })
          }
        })
      }
      if (this.markers.length) {
        this.overlayGroup = new AMap.OverlayGroup(this.markers)
        this.map.add(this.overlayGroup)
      }
    },
    // 视频通话点位
    setPeopleMarker(peopleData) {
      if (peopleData.gridPersonName && peopleData.phone && peopleData.longitude && peopleData.latitude) {
        const content = `
        <div class="amap-marker-inspect-content">
            <van-icon name="manager" />
            <i class="van-icon van-icon-manager"></i>
            <div class="aaaa">${peopleData.gridPersonName}</div>
        </div>`
        const marker = new AMap.Marker({
          position: new AMap.LngLat(peopleData.longitude, peopleData.latitude),
          content: content
        })
        this.markers.push(marker)
        marker.on('click', () => {
          this.$toast.loading('正在呼叫：' + peopleData.gridPersonName)
          this.$eventBus.$emit('trtcCallingCall', {
            gridPersonName: peopleData.gridPersonName,
            telephone: peopleData.phone
          })
        })
        if (this.markers.length) {
          this.overlayGroup = new AMap.OverlayGroup(this.markers)
          this.map.add(this.overlayGroup)
        }
      }
    },
    getPeoplePoint() {
      CampusSecurity.Api.getPeoplePoint({
        longitude: this.center[0],
        latitude: this.center[1]
      }).then(res => {
        if (res.data.data) {
          res.data.data.forEach(item => {
            this.setPeopleMarker(item)
          })
        }
      })
    }
  }
}
</script>
<style scoped lang="less">
@import '~@/assets/style/inspectVisit/inspect/index.less';
</style>
